package com.soulkun.smarthome

import com.google.gson.Gson
import com.google.gson.GsonBuilder
import kotlinx.coroutines.*
import org.junit.Test

import org.junit.Assert.*
import soulkun.library.utils.time.DateUtils
import java.sql.Date
import java.sql.Timestamp
import java.text.SimpleDateFormat
import java.time.LocalDateTime
import java.time.LocalTime
import java.util.concurrent.Executors
import java.util.concurrent.atomic.AtomicInteger

/**
 * Example local unit test, which will execute on the development machine (host).
 *
 * See [testing documentation](http://d.android.com/tools/testing).
 */
class ExampleUnitTest {

    private val coroutineDispatcher = Executors.newFixedThreadPool(2).asCoroutineDispatcher()
    private var job1: Job? = null
    private var job2: Job? = null
    private val count = AtomicInteger()

    @Test
    fun addition_isCorrect() {
        assertEquals(4, 2 + 2)
    }

    @Test
    fun test1() {
        println(1)
    }

    @Test
    fun test() {
        coroutineTest()
        Thread.sleep(1000000)
    }

    private fun coroutineTest() {
        GlobalScope.launch(coroutineDispatcher) {
            println(Thread.currentThread().name + ":test")
            delay(3000)
            count.set(0)
            job1 = GlobalScope.launch(coroutineDispatcher) {
                coroutineTest1()
            }
        }
    }

    private suspend fun coroutineTest1() = coroutineScope {
        while (true) {
            delay(2000)
            ensureActive()
            println(Thread.currentThread().name + ":test1")
            if (count.addAndGet(1) >= 5) {
                println(Thread.currentThread().name + ":test1-cancel")
                job1?.cancel()
                job1 = null
                coroutineTest()
            }
        }
    }

    @Test
    fun testFunction() {
        fun1(1) { string ->
            println(string)
        }
    }

    private fun fun1(result: Int, onComplete: Int.(String) -> Unit) {
        onComplete(result, "111")
    }

    private fun Int.test(int: Int): Int {
        return int
    }

    @Test
    fun testJsonTimestamp() {
        val json = """{
            "timestamp": "2022-04-21 21:54:18.259"
        }"""
        val gson = GsonBuilder().setDateFormat("yyyy-MM-dd hh:mm:ss").create()
        val fromJson = gson.fromJson(json, JsonTimestamp::class.java)
        println(fromJson)
    }

    data class JsonTimestamp(val timestamp: Timestamp)

    @Test
    fun testJoin() {
        val set = setOf<String>("1", "2", "3")
        println(set.joinToString(separator = "#"))
    }

}